package com.blunka.framework.client.ui.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.yak.common.digest.ApplicationUtils;
import org.yak.common.digest.DESUtils;
import org.yak.common.file.FileUtil;

import com.alibaba.fastjson.JSON;
import com.blunka.framework.client.constants.DesignConstant;
import com.blunka.framework.client.constants.InitDesignConfig;
import com.blunka.framework.client.db.druid.DBSQLService;
import com.blunka.framework.client.db.druid.service.ISQLService;
import com.blunka.framework.client.db.entity.BatchSqlEntity;
import com.blunka.framework.client.enums.ModelStates;
import com.blunka.framework.client.enums.ModelType;
import com.blunka.framework.client.ui.AttrPanel;
import com.blunka.framework.client.ui.MainFrame;
import com.blunka.framework.client.ui.TreeModelPanel;
import com.blunka.framework.client.ui.dialog.ProtyDialog;
import com.blunka.framework.client.ui.dialog.ProtyFieldDialog;
import com.blunka.framework.client.ui.dialog.SubmitDialog;
import com.blunka.framework.client.ui.entity.BlkImportTableMetaData;
import com.blunka.framework.client.ui.entity.BlkTableMetaData;
import com.blunka.framework.client.utils.DesignUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * 按钮、功能菜单处理方法
 * @author xuqiang
 *
 */
public class ActionUtils {

	private static final Logger logger = Logger.getLogger(ActionUtils.class);

	/**
	 * 获取本地缓存数据库
	 */
	private static ISQLService localSqlHepler = DBSQLService.getLocalDBService();
	
	/**
	 * 存储复制的节点记录
	 */
	private static List<BlkTableMetaData> copyModelNodeList = new ArrayList<BlkTableMetaData>();

	/**
	 * 创建建模节点
	 * @param title
	 * @param modelType
	 */
	public static void createBlkModel(String title,ModelType modelType){
		new ProtyDialog(title,modelType){
			@Override
			public boolean beforeCallBack(String zhText, String enText) {
				return true;
			}
			
			public void callBack(String zhText,String enText) {
				//获取所选择的树节点
				TreeModelPanel treePanel = TreeModelPanel.newInstance();
				DefaultMutableTreeNode selectNode = treePanel.getSelectTreeNode();
				BlkTableMetaData selectBlkModel = (BlkTableMetaData)selectNode.getUserObject();

				//生成创建节点属性
				BlkTableMetaData node = new BlkTableMetaData();
				node.setFather_tablemetadata_id(selectBlkModel.getTablemetadata_id());
				node.setZh_cn(zhText);
				node.setEn_us(enText);
				//设置节点path路径
				node.setObj_path(treePanel.getTreeNodeDeptPath(enText, selectNode));
				node.setModel_type(modelType);
				//node.setModel_states(ModelStates.FINISHED);
				node.setModel_states(ModelStates.NEW);
				//node.setGuidtag(System.currentTimeMillis());
				node.setOrder_by(treePanel.getTreeNodeIndex(selectNode));

				try{
					//新节点
					DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(node);
					newNode.setUserObject(node);

					//保存数据库
					BlkTableMetaData insertNode = localSqlHepler.insertNode(node);
					if(insertNode !=null){
						logger.info("操作成功");
						DesignUtils.showMessage(MainFrame.getMainFrame(), "操作成功",DesignConstant.PROMIT_TITLE, JOptionPane.INFORMATION_MESSAGE);
						//重新刷新节点属性
						newNode.setUserObject(insertNode);
						//添加成功后，刷新节点
						selectNode.add(newNode);
						treePanel.refreshSelectNode(selectNode);
					}else{
						DesignUtils.showMessage(MainFrame.getMainFrame(), "添加节点失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
					}
				}catch(Exception e){
					DesignUtils.showMessage(MainFrame.getMainFrame(), e.getMessage(),DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
					logger.error("提交建模信息异常",e);
					e.printStackTrace();
				}
			}
		};
	}

	/**
	 * 创建表或者试图
	 * @param title
	 * @param modelType
	 */
	public static void createTableOrView(String title,ModelType modelType){
		new ProtyDialog(title,modelType){
			@Override
			public boolean beforeCallBack(String zhText, String enText) {
				return true;
			}
			@Override
			public void callBack(String zhText, String enText) {
				//获取所选择的树节点
				TreeModelPanel treePanel = TreeModelPanel.newInstance();
				DefaultMutableTreeNode selectNode = treePanel.getSelectTreeNode();
				BlkTableMetaData selectBlkModel = (BlkTableMetaData)selectNode.getUserObject();

				//生成创建节点属性
				BlkTableMetaData node = new BlkTableMetaData();
				node.setFather_tablemetadata_id(selectBlkModel.getTablemetadata_id());
				node.setZh_cn(zhText);
				node.setEn_us(enText);
				//设置节点path路径
				node.setObj_path(treePanel.getTreeNodeDeptPath(enText, selectNode));
				node.setModel_type(modelType);
				node.setModel_states(ModelStates.NEW);
				//node.setGuidtag(System.currentTimeMillis());
				node.setOrder_by(treePanel.getTreeNodeIndex(selectNode));

				try{
					//新节点
					DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(node);
					newNode.setUserObject(node);


					//保存数据库
					BlkTableMetaData insertNode = localSqlHepler.insertTableNode(node);
					if(insertNode !=null){
						logger.info("操作成功");
						DesignUtils.showMessage(MainFrame.getMainFrame(), "操作成功",DesignConstant.PROMIT_TITLE, JOptionPane.INFORMATION_MESSAGE);
						//重新刷新节点属性
						newNode.setUserObject(insertNode);
						//添加成功后，刷新节点
						selectNode.add(newNode);
						treePanel.refreshSelectNode(selectNode);
					}else{
						DesignUtils.showMessage(MainFrame.getMainFrame(), "添加节点失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
					}

				}catch(Exception e){
					DesignUtils.showMessage(MainFrame.getMainFrame(), e.getMessage(),DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
					logger.error("提交建模信息异常",e);
				}
			}

		};
	}

	/**
	 * 创建字段
	 * @param title
	 * @param modelType
	 */
	public static void createField(String title,ModelType modelType){
		new ProtyFieldDialog(title,modelType){
			@Override
			public void callBack(BlkTableMetaData newBlkModel) {
				//获取所选择的树节点
				TreeModelPanel treePanel = TreeModelPanel.newInstance();
				DefaultMutableTreeNode selectNode = treePanel.getSelectTreeNode();
				BlkTableMetaData selectBlkModel = (BlkTableMetaData)selectNode.getUserObject();
				//设置父节点
				newBlkModel.setFather_tablemetadata_id(selectBlkModel.getTablemetadata_id());
				//设置节点path路径
				newBlkModel.setObj_path(treePanel.getTreeNodeDeptPath(newBlkModel.getEn_us(), selectNode));
				newBlkModel.setOrder_by(treePanel.getTreeNodeIndex(selectNode));
				newBlkModel.setModel_states(ModelStates.NEW);
				try{
					//新节点
					DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(newBlkModel);
					newNode.setUserObject(newBlkModel);


					//保存数据库
					BlkTableMetaData insertNode = localSqlHepler.insertField(newBlkModel,selectBlkModel);
					if(insertNode !=null){
						logger.info("操作成功");
						DesignUtils.showMessage(MainFrame.getMainFrame(), "操作成功",DesignConstant.PROMIT_TITLE, JOptionPane.INFORMATION_MESSAGE);
						//重新刷新节点属性
						newNode.setUserObject(insertNode);
						//添加成功后，刷新节点
						selectNode.add(newNode);
						treePanel.refreshSelectNode(selectNode);
					}else{
						DesignUtils.showMessage(MainFrame.getMainFrame(), "添加节点失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
					}

				}catch(Exception e){
					DesignUtils.showMessage(MainFrame.getMainFrame(), e.getMessage(),DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
					logger.error("提交建模信息异常",e);
				}
			}

		};
	}

	/**
	 * 修改字段
	 * @param title
	 * @param modelType
	 */
	public static void modifyField(String title,ModelType modelType){
		//获取所选择的树节点
		TreeModelPanel treePanel = TreeModelPanel.newInstance();
		DefaultMutableTreeNode selectNode = treePanel.getSelectTreeNode();
		BlkTableMetaData selectBlkModel = (BlkTableMetaData)selectNode.getUserObject();

		//获取父节点
		DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)selectNode.getParent();
		new ProtyFieldDialog(title,selectBlkModel){
			@Override
			public void callBack(BlkTableMetaData newBlkModel) {

				newBlkModel.setTablemetadata_id(selectBlkModel.getTablemetadata_id());
				//设置父节点
				newBlkModel.setFather_tablemetadata_id(selectBlkModel.getFather_tablemetadata_id());
				//设置节点path路径
				newBlkModel.setObj_path(treePanel.getTreeNodeDeptPath(newBlkModel.getEn_us(), parentNode));
				newBlkModel.setOrder_by(selectBlkModel.getOrder_by());
				if(selectBlkModel.getModel_states() != ModelStates.NEW){
					//旧节点信息的状态如果不为NEW修改后需要将新节点状态变成change
					newBlkModel.setModel_states(ModelStates.CHANGED);
				}
				try{
					//更新所选节点内容
					selectNode.setUserObject(newBlkModel);


					//保存数据库
					BlkTableMetaData updateNode = localSqlHepler.updateField(newBlkModel,(BlkTableMetaData)parentNode.getUserObject());
					if(updateNode !=null){
						logger.info("操作成功");
						DesignUtils.showMessage(MainFrame.getMainFrame(), "操作成功",DesignConstant.PROMIT_TITLE, JOptionPane.INFORMATION_MESSAGE);
						//重新刷新节点属性
						selectNode.setUserObject(updateNode);
						//添加成功后，刷新节点
						//AttrPanel.newInstance().refreshTableData((BlkTableMetaData)selectNode.getUserObject());
						DefaultTreeModel DTreeModel = (DefaultTreeModel) treePanel.getTree().getModel();
						DTreeModel.reload();
				        TreePath visiblePath = new TreePath(DTreeModel.getPathToRoot(selectNode));
				        treePanel.getTree().setSelectionPath(visiblePath);
					}else{
						DesignUtils.showMessage(MainFrame.getMainFrame(), "添加节点失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
					}

				}catch(Exception e){
					DesignUtils.showMessage(MainFrame.getMainFrame(), "提交异常："+e.getMessage(),DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
					logger.error("提交建模信息异常",e);
				}
			}

		};
	}

	/**
	 * 删除选中节点
	 */
	public static void delNode(){
		TreeModelPanel treePanel = TreeModelPanel.newInstance();
		DefaultMutableTreeNode selectNode = treePanel.getSelectTreeNode();
		BlkTableMetaData selectBlkModel = (BlkTableMetaData)selectNode.getUserObject();
		String msg ="确定需要删除选中的节点及其子节点？删除后将不可恢复！";
		if(selectBlkModel.getModel_type() == ModelType.ATTRIBUTE){
			msg = "确定需要删除选中的节点？删除后将不可恢复！";
		}
		if(DesignUtils.showConfirm(MainFrame.getMainFrame(), msg) == JOptionPane.YES_OPTION){
			logger.info("删除");

			List<BatchSqlEntity> sqlList = new ArrayList<BatchSqlEntity>();
			parseDelModelNode(selectNode,sqlList);
			try{
				localSqlHepler.batchModelNode(sqlList);
				DesignUtils.showMessage(MainFrame.getMainFrame(), "操作成功",DesignConstant.PROMIT_TITLE, JOptionPane.INFORMATION_MESSAGE);
				selectNode.removeFromParent();
				treePanel.getTree().updateUI();
			}catch(Exception e){
				logger.error("删除节点异常",e);
				DesignUtils.showMessage(MainFrame.getMainFrame(), "操作失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
			}

		}

	}
	
	/**
	 * 复制选中表或者试图所有子节点
	 */
	public static void copyChildModelNode() {
		TreeModelPanel treePanel = TreeModelPanel.newInstance();
		DefaultMutableTreeNode selectNode = treePanel.getSelectTreeNode();
		int childCount = selectNode.getChildCount();
		for(int i=0;i<childCount;i++) {
			DefaultMutableTreeNode chidNode = (DefaultMutableTreeNode)selectNode.getChildAt(i);
			BlkTableMetaData childBlkModel = (BlkTableMetaData)chidNode.getUserObject();
			if(!copyModelNodeList.contains(childBlkModel)) {
				copyModelNodeList.add(childBlkModel);
			}
		}
		DesignUtils.showMessage(MainFrame.getMainFrame(), "复制成功",DesignConstant.PROMIT_TITLE, JOptionPane.INFORMATION_MESSAGE);
	}

	/**
	 * 复制单个节点
	 */
	public static void copyModelNode() {
		TreeModelPanel treePanel = TreeModelPanel.newInstance();
		DefaultMutableTreeNode selectNode = treePanel.getSelectTreeNode();
		BlkTableMetaData childBlkModel = (BlkTableMetaData)selectNode.getUserObject();
		if(!copyModelNodeList.contains(childBlkModel)) {
			copyModelNodeList.add(childBlkModel);
		}
		DesignUtils.showMessage(MainFrame.getMainFrame(), "复制成功",DesignConstant.PROMIT_TITLE, JOptionPane.INFORMATION_MESSAGE);
	}
	
	/**
	 * 粘贴复制的节点
	 */
	public static void pasteModelNodes() {
		if(copyModelNodeList.isEmpty()) {
			DesignUtils.showMessage(MainFrame.getMainFrame(), "剪切板中没有需要粘贴的数据，请先复制",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
			return ;
		}
		try {
			//获取选中的节点为父节点
			TreeModelPanel treePanel = TreeModelPanel.newInstance();
			DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)treePanel.getSelectTreeNode();
			BlkTableMetaData parentBlkMetaData = (BlkTableMetaData)parentNode.getUserObject();
			int count = 0;
			for(BlkTableMetaData blkMetaData : copyModelNodeList) {
				BlkTableMetaData newKlkMetaData = (BlkTableMetaData) blkMetaData.clone();
				//newKlkMetaData.setTablemetadata_id(DesignUtils.getRandom());
				newKlkMetaData.setFather_tablemetadata_id(parentBlkMetaData.getTablemetadata_id());
				newKlkMetaData.setObj_path(parentBlkMetaData.getObj_path()+"/"+blkMetaData.getEn_us());
				newKlkMetaData.setModel_states(ModelStates.NEW);
				newKlkMetaData.setOrder_by(parentNode.getChildCount()+count+1);
				if(localSqlHepler.queryTableOrViewFieldExists(newKlkMetaData,parentBlkMetaData.getEn_us())) {
					//logger.warn("系统警告，节点："+blkMetaData.getEn_us()+",已经存在，复制的节点自动重命名为："+newKlkMetaData.getEn_us()+"_1");
					new ProtyDialog(blkMetaData.getEn_us()+",已经存在,请重新定义",ModelType.GROUPS){
						@Override
						public boolean beforeCallBack(String zhText, String enText) {
							BlkTableMetaData checkMetaData = new BlkTableMetaData();
							checkMetaData.setEn_us(enText);
							checkMetaData.setZh_cn(zhText);
							checkMetaData.setFather_tablemetadata_id(newKlkMetaData.getFather_tablemetadata_id());
							try {
								if(localSqlHepler.queryTableOrViewFieldExists(checkMetaData,parentBlkMetaData.getEn_us())) {
									DesignUtils.showMessage(MainFrame.getMainFrame(), "系统警告，节点："+checkMetaData.getEn_us()+",已经存在,请重新命名",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
									return false;
								}
							}catch(Exception e) {
								logger.error("重命名节点信息异常",e);
								return false;
							}
							return true;
						}
						
						public void callBack(String zhText,String enText) {
							newKlkMetaData.setEn_us(enText);
							newKlkMetaData.setZh_cn(zhText);
							try {
								BlkTableMetaData new_blkMetaData = localSqlHepler.insertField(newKlkMetaData,parentBlkMetaData);
								
								DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(new_blkMetaData);
								newNode.setUserObject(new_blkMetaData);
								parentNode.add(newNode);
							}catch(Exception e) {
								logger.error("节点："+blkMetaData.getEn_us()+"添加异常",e);
							}
						}
					};
					
				}else {
					BlkTableMetaData new_blkMetaData = localSqlHepler.insertField(newKlkMetaData,parentBlkMetaData);
					
					DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(new_blkMetaData);
					newNode.setUserObject(new_blkMetaData);
					parentNode.add(newNode);
				}
				
				
				treePanel.refreshSelectNode(parentNode);
				count++;
			}
			
			copyModelNodeList.clear();
			
		}catch(Exception e) {
			logger.error("复制节点异常",e);
		}
	}

	/**
	 * 修改或者保存视图语句
	 * @param sql
	 */
	public static void saveOrModifyViewSql(String viewSqlConfig){
		//获取所选择的树节点
		TreeModelPanel treePanel = TreeModelPanel.newInstance();
		DefaultMutableTreeNode selectNode = treePanel.getSelectTreeNode();
		BlkTableMetaData selectBlkModel = (BlkTableMetaData)selectNode.getUserObject();
		if(selectBlkModel.getModel_type() != ModelType.VIEW){
			DesignUtils.showMessage(null, "当前所选择的业务节点为非视图节点，不可进行视图sql编辑", "系统提示", JOptionPane.WARNING_MESSAGE);
			return;
		}
		selectBlkModel.setView_sql(viewSqlConfig);
		if(selectBlkModel.getModel_states() != ModelStates.NEW){
			//非新建状态的节点修改后需要将节点变更成修改状态
			selectBlkModel.setModel_states(ModelStates.CHANGED);
		}
		String updateViewSql = "UPDATE BLK_TABLE_METADATA SET VIEW_SQL=?,MODEL_STATES=? WHERE TABLEMETADATA_ID=?";
		BatchSqlEntity entitySql = new BatchSqlEntity();
		entitySql.setSql(updateViewSql);
		Object[] param = {selectBlkModel.getView_sql(),selectBlkModel.getModel_states().getIndex(),selectBlkModel.getTablemetadata_id()};
		entitySql.setParams(param);
		List<BatchSqlEntity> sqlList = new ArrayList<BatchSqlEntity>();
		sqlList.add(entitySql);

		try{
			localSqlHepler.batchModelNode(sqlList);
			DesignUtils.showMessage(MainFrame.getMainFrame(), "操作成功",DesignConstant.PROMIT_TITLE, JOptionPane.INFORMATION_MESSAGE);
			//刷新节点
			AttrPanel.newInstance().refreshTableData(selectBlkModel);
		}catch(Exception e){
			logger.error("更新视图语句异常",e);
			DesignUtils.showMessage(MainFrame.getMainFrame(), "操作失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
		}
	}

	/**
	 * 解析需要删除的节点属性
	 * @param selectNode
	 * @param sqlList
	 */
	private static void parseDelModelNode(DefaultMutableTreeNode selectNode,List<BatchSqlEntity> sqlList){
		BlkTableMetaData selectBlkModel = (BlkTableMetaData)selectNode.getUserObject();
		if(selectBlkModel.getModel_states() == ModelStates.NEW){
			//当前字段为新建的删除，直接删除缓存数据库中的字段信息，不需要标记状态为删除，只有已经在服务器数据库中存在数据才需要标记为删除字段
			String sql = "DELETE FROM BLK_TABLE_METADATA WHERE TABLEMETADATA_ID='"+selectBlkModel.getTablemetadata_id()+"'";
			BatchSqlEntity entitySql = new BatchSqlEntity();
			entitySql.setSql(sql);
			sqlList.add(entitySql);

			//判断当前节点是否存在子节点
			if(selectNode.getChildCount()>0){
				logger.info("存在子节点，继续递归查询");
				for(int i=0;i<selectNode.getChildCount();i++){
					parseDelModelNode((DefaultMutableTreeNode)selectNode.getChildAt(i),sqlList);
				}
			}
		}else{
			if(selectBlkModel.getModel_type() == ModelType.ATTRIBUTE){
				//删除建模节点记录
				String sql = "UPDATE BLK_TABLE_METADATA SET MODEL_STATES='"+ModelStates.DELETE.getIndex()+"' WHERE TABLEMETADATA_ID='"+selectBlkModel.getTablemetadata_id()+"'";
				BatchSqlEntity entitySql = new BatchSqlEntity();
				entitySql.setSql(sql);
				sqlList.add(entitySql);

			}else if(selectBlkModel.getModel_type() == ModelType.TABLE){
				//删除表对应的所有字段
				String sql = "UPDATE BLK_TABLE_METADATA SET MODEL_STATES='"+ModelStates.DELETE.getIndex()+"' WHERE FATHER_TABLEMETADATA_ID =(SELECT TABLEMETADATA_ID FROM (SELECT TABLEMETADATA_ID FROM BLK_TABLE_METADATA WHERE TABLEMETADATA_ID='"+selectBlkModel.getTablemetadata_id()+"')C)";
				BatchSqlEntity entitySql = new BatchSqlEntity();
				entitySql.setSql(sql);
				sqlList.add(entitySql);
				//删除当前节点信息
				sql = "UPDATE BLK_TABLE_METADATA SET MODEL_STATES='"+ModelStates.DELETE.getIndex()+"' WHERE TABLEMETADATA_ID='"+selectBlkModel.getTablemetadata_id()+"'";
				BatchSqlEntity entitySql2 = new BatchSqlEntity();
				entitySql2.setSql(sql);
				sqlList.add(entitySql2);
			}else if(selectBlkModel.getModel_type() == ModelType.VIEW){
				//删除试图对应的所有字段
				String sql = "UPDATE BLK_TABLE_METADATA SET MODEL_STATES='"+ModelStates.DELETE.getIndex()+"' WHERE FATHER_TABLEMETADATA_ID =(SELECT TABLEMETADATA_ID FROM (SELECT TABLEMETADATA_ID FROM BLK_TABLE_METADATA WHERE TABLEMETADATA_ID='"+selectBlkModel.getTablemetadata_id()+"')C)";
				BatchSqlEntity entitySql = new BatchSqlEntity();
				entitySql.setSql(sql);
				sqlList.add(entitySql);
				//删除当前节点信息
				sql = "UPDATE BLK_TABLE_METADATA SET MODEL_STATES='"+ModelStates.DELETE.getIndex()+"' WHERE TABLEMETADATA_ID='"+selectBlkModel.getTablemetadata_id()+"'";
				BatchSqlEntity entitySql2 = new BatchSqlEntity();
				entitySql2.setSql(sql);
				sqlList.add(entitySql2);

			}else{
				//删除建模节点记录
				String sql = "UPDATE BLK_TABLE_METADATA SET MODEL_STATES='"+ModelStates.DELETE.getIndex()+"' WHERE TABLEMETADATA_ID='"+selectBlkModel.getTablemetadata_id()+"'";
				BatchSqlEntity entitySql = new BatchSqlEntity();
				entitySql.setSql(sql);
				sqlList.add(entitySql);

				//判断当前节点是否存在子节点
				if(selectNode.getChildCount()>0){
					logger.info("存在子节点，继续递归查询");
					for(int i=0;i<selectNode.getChildCount();i++){
						parseDelModelNode((DefaultMutableTreeNode)selectNode.getChildAt(i),sqlList);
					}
				}
			}
		}
	}

	/**
	 * 同目录下节点上移
	 */
	public static void MoveNode(){
		TreeModelPanel treePanel = TreeModelPanel.newInstance();
		DefaultTreeModel DTreeModel = (DefaultTreeModel) treePanel.getTree().getModel();
		//当前节点
		DefaultMutableTreeNode selectNode = treePanel.getSelectTreeNode();
		//BlkTableMetaData selectModel = (BlkTableMetaData)selectNode.getUserObject();
		//获取父节点
		DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)selectNode.getParent();
		//获取当前节点在父节点中的位置索引
		int index = DTreeModel.getIndexOfChild(selectNode.getParent(), selectNode);
		if (selectNode.isRoot() || index <= 0) {
			logger.info("当前节点无法进行上移排序");
			return;
		}
		//位置互换
        DTreeModel.insertNodeInto(selectNode, (DefaultMutableTreeNode)selectNode.getParent(), index - 1);
        DTreeModel.reload();
        TreePath visiblePath = new TreePath(DTreeModel.getPathToRoot(selectNode));
        treePanel.getTree().setSelectionPath(visiblePath);
        List<BatchSqlEntity> sqlList = new ArrayList<BatchSqlEntity>();
        for(int i=0;i<parentNode.getChildCount();i++) {
        	DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)parentNode.getChildAt(i);
        	BlkTableMetaData childModel = (BlkTableMetaData)childNode.getUserObject();
        	childModel.setOrder_by(i);
        	
        	BatchSqlEntity entitySql = new BatchSqlEntity();
    		if(childModel.getModel_states() == ModelStates.NEW){
    			entitySql.setSql("UPDATE BLK_TABLE_METADATA SET ORDER_BY="+childModel.getOrder_by()+" WHERE TABLEMETADATA_ID='"+childModel.getTablemetadata_id()+"'");
    		}else{
    			entitySql.setSql("UPDATE BLK_TABLE_METADATA SET ORDER_BY="+childModel.getOrder_by()+", MODEL_STATES='"+ModelStates.CHANGED.getIndex()+"' WHERE TABLEMETADATA_ID='"+childModel.getTablemetadata_id()+"'");
    			childModel.setModel_states(ModelStates.CHANGED);
    		}
    		childNode.setUserObject(childModel);
    		sqlList.add(entitySql);
        }
        try{
			localSqlHepler.batchModelNode(sqlList);
		}catch(Exception e){
			logger.error("节点移动异常",e);
			DesignUtils.showMessage(MainFrame.getMainFrame(), "操作失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
		}
		/*//获取上一个节点
		DefaultMutableTreeNode previousNode = (DefaultMutableTreeNode)parentNode.getChildAt(index-1);
		BlkTableMetaData previousModel = (BlkTableMetaData)previousNode.getUserObject();
		//两个节点排序互换
		int selectModelOrder = selectModel.getOrder_by();
		int previousModelOrder = previousModel.getOrder_by();
		selectModel.setOrder_by(previousModelOrder);
		previousModel.setOrder_by(selectModelOrder);
		selectNode.setUserObject(selectModel);
		previousNode.setUserObject(previousModel);
		List<BatchSqlEntity> sqlList = new ArrayList<BatchSqlEntity>();
		BatchSqlEntity entitySql = new BatchSqlEntity();
		if(selectModel.getModel_states() == ModelStates.NEW){
			entitySql.setSql("UPDATE BLK_TABLE_METADATA SET ORDER_BY="+selectModel.getOrder_by()+" WHERE TABLEMETADATA_ID='"+selectModel.getTablemetadata_id()+"'");
		}else{
			entitySql.setSql("UPDATE BLK_TABLE_METADATA SET ORDER_BY="+selectModel.getOrder_by()+", MODEL_STATES='"+ModelStates.CHANGED.getIndex()+"' WHERE TABLEMETADATA_ID='"+selectModel.getTablemetadata_id()+"'");
			selectModel.setModel_states(ModelStates.CHANGED);
			selectNode.setUserObject(selectModel);
		}
		sqlList.add(entitySql);
		BatchSqlEntity entity = new BatchSqlEntity();
		if(previousModel.getModel_states() == ModelStates.NEW){
			entity.setSql("UPDATE BLK_TABLE_METADATA SET ORDER_BY="+previousModel.getOrder_by()+" WHERE TABLEMETADATA_ID='"+previousModel.getTablemetadata_id()+"'");
		}else{
			entity.setSql("UPDATE BLK_TABLE_METADATA SET ORDER_BY="+previousModel.getOrder_by()+", MODEL_STATES='"+ModelStates.CHANGED.getIndex()+"' WHERE TABLEMETADATA_ID='"+previousModel.getTablemetadata_id()+"'");
			previousModel.setModel_states(ModelStates.CHANGED);
			previousNode.setUserObject(previousModel);
		}
		sqlList.add(entity);
		try{
			localSqlHepler.batchModelNode(sqlList);
			//位置互换
	        DTreeModel.insertNodeInto(selectNode, (DefaultMutableTreeNode)selectNode.getParent(), index - 1);
	        DTreeModel.reload();
	        TreePath visiblePath = new TreePath(DTreeModel.getPathToRoot(selectNode));
	        treePanel.getTree().setSelectionPath(visiblePath);
		}catch(Exception e){
			logger.error("节点移动异常",e);
			DesignUtils.showMessage(MainFrame.getMainFrame(), "操作失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
		}*/
	}

	/**
	 * 同目录下的节点下移
	 */
	public static void DownNode(){
		TreeModelPanel treePanel = TreeModelPanel.newInstance();
		DefaultTreeModel DTreeModel = (DefaultTreeModel) treePanel.getTree().getModel();
		//当前节点
		DefaultMutableTreeNode selectNode = treePanel.getSelectTreeNode();
		//BlkTableMetaData selectModel = (BlkTableMetaData)selectNode.getUserObject();
		//获取父节点
		DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)selectNode.getParent();
		//获取当前节点在父节点中的位置索引
		int index = DTreeModel.getIndexOfChild(parentNode, selectNode);
		if (selectNode.isRoot() || index >= parentNode.getChildCount()-1) {
			logger.info("当前节点无法进行下移排序");
			return;
		}
		//位置互换
		DTreeModel.insertNodeInto(selectNode, (DefaultMutableTreeNode)selectNode.getParent(), index + 1);
        DTreeModel.reload();
        TreePath visiblePath = new TreePath(DTreeModel.getPathToRoot(selectNode));
        treePanel.getTree().setSelectionPath(visiblePath);
        List<BatchSqlEntity> sqlList = new ArrayList<BatchSqlEntity>();
        for(int i=0;i<parentNode.getChildCount();i++) {
        	DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)parentNode.getChildAt(i);
        	BlkTableMetaData childModel = (BlkTableMetaData)childNode.getUserObject();
        	childModel.setOrder_by(i);
        	
        	BatchSqlEntity entitySql = new BatchSqlEntity();
    		if(childModel.getModel_states() == ModelStates.NEW){
    			entitySql.setSql("UPDATE BLK_TABLE_METADATA SET ORDER_BY="+childModel.getOrder_by()+" WHERE TABLEMETADATA_ID='"+childModel.getTablemetadata_id()+"'");
    		}else{
    			entitySql.setSql("UPDATE BLK_TABLE_METADATA SET ORDER_BY="+childModel.getOrder_by()+", MODEL_STATES='"+ModelStates.CHANGED.getIndex()+"' WHERE TABLEMETADATA_ID='"+childModel.getTablemetadata_id()+"'");
    			childModel.setModel_states(ModelStates.CHANGED);
    		}
    		childNode.setUserObject(childModel);
    		sqlList.add(entitySql);
        }
        try{
			localSqlHepler.batchModelNode(sqlList);
		}catch(Exception e){
			logger.error("节点移动异常",e);
			DesignUtils.showMessage(MainFrame.getMainFrame(), "操作失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
		}
		
		//获取上一个节点
		/*DefaultMutableTreeNode nextNode = (DefaultMutableTreeNode)parentNode.getChildAt(index+1);
		BlkTableMetaData previousModel = (BlkTableMetaData)nextNode.getUserObject();
		//两个节点排序互换
		int selectModelOrder = selectModel.getOrder_by();
		int previousModelOrder = previousModel.getOrder_by();
		selectModel.setOrder_by(previousModelOrder);
		previousModel.setOrder_by(selectModelOrder);
		selectNode.setUserObject(selectModel);
		nextNode.setUserObject(previousModel);
		List<BatchSqlEntity> sqlList = new ArrayList<BatchSqlEntity>();
		BatchSqlEntity entitySql = new BatchSqlEntity();
		if(selectModel.getModel_states() == ModelStates.NEW){
			entitySql.setSql("UPDATE BLK_TABLE_METADATA SET ORDER_BY="+selectModel.getOrder_by()+" WHERE TABLEMETADATA_ID='"+selectModel.getTablemetadata_id()+"'");
		}else{
			entitySql.setSql("UPDATE BLK_TABLE_METADATA SET ORDER_BY="+selectModel.getOrder_by()+", MODEL_STATES='"+ModelStates.CHANGED.getIndex()+"' WHERE TABLEMETADATA_ID='"+selectModel.getTablemetadata_id()+"'");
			selectModel.setModel_states(ModelStates.CHANGED);
			selectNode.setUserObject(selectModel);
		}
		sqlList.add(entitySql);
		BatchSqlEntity entity = new BatchSqlEntity();
		if(previousModel.getModel_states() == ModelStates.NEW){
			entity.setSql("UPDATE BLK_TABLE_METADATA SET ORDER_BY="+previousModel.getOrder_by()+" WHERE TABLEMETADATA_ID='"+previousModel.getTablemetadata_id()+"'");
		}else{
			entity.setSql("UPDATE BLK_TABLE_METADATA SET ORDER_BY="+previousModel.getOrder_by()+", MODEL_STATES='"+ModelStates.CHANGED.getIndex()+"' WHERE TABLEMETADATA_ID='"+previousModel.getTablemetadata_id()+"'");
			previousModel.setModel_states(ModelStates.CHANGED);
			nextNode.setUserObject(previousModel);
		}
		sqlList.add(entity);
		try{
			localSqlHepler.batchModelNode(sqlList);
			//位置互换
	        DTreeModel.insertNodeInto(selectNode, (DefaultMutableTreeNode)selectNode.getParent(), index + 1);
	        DTreeModel.reload();
	        TreePath visiblePath = new TreePath(DTreeModel.getPathToRoot(selectNode));
	        treePanel.getTree().setSelectionPath(visiblePath);
		}catch(Exception e){
			logger.error("节点移动异常",e);
			DesignUtils.showMessage(MainFrame.getMainFrame(), "操作失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
		}*/
	}
	
	/**
	 * 节点以及子节点置new
	 */
	public static void pasteModelNodesNew() {
		List<BatchSqlEntity> sqlList = new ArrayList<BatchSqlEntity>();
		
		TreeModelPanel treePanel = TreeModelPanel.newInstance();
		//当前节点
		DefaultMutableTreeNode selectNode = treePanel.getSelectTreeNode();
		BlkTableMetaData selectModel = (BlkTableMetaData)selectNode.getUserObject();
		if(DesignUtils.showConfirm(MainFrame.getMainFrame(), "确定将当前节点以及子节点置为NEW？") == JOptionPane.OK_OPTION){
			
			if(selectModel.getModel_states() == ModelStates.NEW) {
				//新节点无需设置
				return ;
			}
			selectModel.setModel_states(ModelStates.NEW);
			selectNode.setUserObject(selectModel);
			//提交本地数据库
			String sql = "UPDATE BLK_TABLE_METADATA SET MODEL_STATES='"+ModelStates.NEW.getIndex()+"' WHERE TABLEMETADATA_ID='"+selectModel.getTablemetadata_id()+"'";
			BatchSqlEntity entitySql2 = new BatchSqlEntity();
			entitySql2.setSql(sql);
			sqlList.add(entitySql2);
			setNodesNew(selectNode,sqlList);
			

			try{
				localSqlHepler.batchModelNode(sqlList);
				AttrPanel.newInstance().refreshTableData(selectModel);
			}catch(Exception e){
				logger.error("节点置NEW异常",e);
				DesignUtils.showMessage(MainFrame.getMainFrame(), "操作失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
			}
		}
	}
	
	/**
	 * 递归置new
	 * @param parentTreeNode
	 * @param sqlList
	 */
	private static void setNodesNew(DefaultMutableTreeNode parentTreeNode,List<BatchSqlEntity> sqlList) {
		for(int i=0;i<parentTreeNode.getChildCount();i++) {
			DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)parentTreeNode.getChildAt(i);
			if(childNode.getChildCount()>0) {
				setNodesChanged(childNode,sqlList);
			}else {
				BlkTableMetaData childModel = (BlkTableMetaData)childNode.getUserObject();
				if(childModel.getModel_states() == ModelStates.NEW) {
					//新节点无需设置
					continue;
				}else {
					childModel.setModel_states(ModelStates.NEW);
					childNode.setUserObject(childModel);
					//提交本地数据库
					String sql = "UPDATE BLK_TABLE_METADATA SET MODEL_STATES='"+ModelStates.NEW.getIndex()+"' WHERE TABLEMETADATA_ID='"+childModel.getTablemetadata_id()+"'";
					BatchSqlEntity entitySql2 = new BatchSqlEntity();
					entitySql2.setSql(sql);
					sqlList.add(entitySql2);
				}
			}
		}
	}
	
	/**
	 * 置节点changed
	 */
	public static void pasteModelNodesChanged() {
		List<BatchSqlEntity> sqlList = new ArrayList<BatchSqlEntity>();
		
		TreeModelPanel treePanel = TreeModelPanel.newInstance();
		//当前节点
		DefaultMutableTreeNode selectNode = treePanel.getSelectTreeNode();
		if(DesignUtils.showConfirm(MainFrame.getMainFrame(), "确定将当前节点以及子节点置为CHANGED？") == JOptionPane.OK_OPTION){
			BlkTableMetaData selectModel = (BlkTableMetaData)selectNode.getUserObject();
			if(selectModel.getModel_states() == ModelStates.NEW) {
				//新节点无需设置
				return ;
			}
			selectModel.setModel_states(ModelStates.CHANGED);
			selectNode.setUserObject(selectModel);
			//提交本地数据库
			String sql = "UPDATE BLK_TABLE_METADATA SET MODEL_STATES='"+ModelStates.CHANGED.getIndex()+"' WHERE TABLEMETADATA_ID='"+selectModel.getTablemetadata_id()+"'";
			BatchSqlEntity entitySql2 = new BatchSqlEntity();
			entitySql2.setSql(sql);
			sqlList.add(entitySql2);
			//递归子节点
			setNodesChanged(selectNode,sqlList);
			try{
				localSqlHepler.batchModelNode(sqlList);
				AttrPanel.newInstance().refreshTableData(selectModel);
			}catch(Exception e){
				logger.error("节点置CHANGED异常",e);
				DesignUtils.showMessage(MainFrame.getMainFrame(), "操作失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
			}
		}
	}
	/**
	 * 递归置changed
	 * @param parentTreeNode
	 * @param sqlList
	 */
	private static void setNodesChanged(DefaultMutableTreeNode parentTreeNode,List<BatchSqlEntity> sqlList) {
		for(int i=0;i<parentTreeNode.getChildCount();i++) {
			DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)parentTreeNode.getChildAt(i);
			if(childNode.getChildCount()>0) {
				setNodesChanged(childNode,sqlList);
			}else {
				BlkTableMetaData childModel = (BlkTableMetaData)childNode.getUserObject();
				if(childModel.getModel_states() == ModelStates.NEW) {
					//新节点无需设置
					continue;
				}else {
					childModel.setModel_states(ModelStates.CHANGED);
					childNode.setUserObject(childModel);
					//提交本地数据库
					String sql = "UPDATE BLK_TABLE_METADATA SET MODEL_STATES='"+ModelStates.CHANGED.getIndex()+"' WHERE TABLEMETADATA_ID='"+childModel.getTablemetadata_id()+"'";
					BatchSqlEntity entitySql2 = new BatchSqlEntity();
					entitySql2.setSql(sql);
					sqlList.add(entitySql2);
				}
			}
		}
	}
	
	/**
	 * 导入节点
	 */
	public static void pasteImportNodes() {
		//定义批量执行sql
		List<BatchSqlEntity> executeSqlList = new ArrayList<BatchSqlEntity>();
		
		//获取需要导入的父节点信息
		TreeModelPanel treePanel = TreeModelPanel.newInstance();
		DefaultMutableTreeNode selectNode = treePanel.getSelectTreeNode();
		BlkTableMetaData selectModel = (BlkTableMetaData)selectNode.getUserObject();
		try {
			JFileChooser chooser = new JFileChooser();// 创建文件选择器
			FileNameExtensionFilter filter = new FileNameExtensionFilter(
			        ".bkfm", "bkfm");
			chooser.setFileFilter(filter);
	        int option = chooser.showOpenDialog(MainFrame.getMainFrame());// 打开文件保存对话框
	        if (option == JFileChooser.APPROVE_OPTION) {// 处理文件保存操作
	            File file = chooser.getSelectedFile();// 获取用户选择的文件
	            //读取文件内容
	            String importFileStr =  new String (FileUtil.readFile2Byte(file));
	            importFileStr = ApplicationUtils.HexadecimalStr2Str(importFileStr);
	            importFileStr = DESUtils.decryption(importFileStr);
	            //导入文件
	            BlkImportTableMetaData bkfmImpEntity = JSON.parseObject(importFileStr, BlkImportTableMetaData.class);
	            DefaultMutableTreeNode importRootNode = new DefaultMutableTreeNode();
	            BlkTableMetaData importRootModel = new BlkTableMetaData();
	            BeanUtils.copyProperties(bkfmImpEntity, importRootModel);
	            //将当前导入文件的根节点的所属父节点设置为选中的节点
	            importRootModel.setFather_tablemetadata_id(selectModel.getTablemetadata_id());
	            importRootNode.setUserObject(importRootModel);
	            //将新导入的节点置new
	            importRootModel.setModel_states(ModelStates.NEW);
	            if(importRootModel.getModel_type() == ModelType.TABLE || importRootModel.getModel_type() == ModelType.VIEW) {
	            	if(localSqlHepler.queryTableOrViewExists(importRootModel)) {
	    				new ProtyDialog("表或视图："+importRootModel.getEn_us()+",已经存在,请重新定义",ModelType.TABLE){
							@Override
							public boolean beforeCallBack(String zhText, String enText)throws Exception {
								BlkTableMetaData checkMetaData = new BlkTableMetaData();
								checkMetaData.setEn_us(enText);
								checkMetaData.setZh_cn(zhText);
								checkMetaData.setFather_tablemetadata_id(importRootModel.getFather_tablemetadata_id());
								if(localSqlHepler.queryTableOrViewExists(checkMetaData)) {
									DesignUtils.showMessage(MainFrame.getMainFrame(), "系统警告，节点："+checkMetaData.getEn_us()+",已经存在,请重新命名",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
									return false;
								}
								return true;
							}
							
							public void callBack(String zhText,String enText)throws Exception {
								importRootModel.setEn_us(enText);
								importRootModel.setZh_cn(zhText);
								executeSqlList.add(localSqlHepler.getInsertTableNodeSql(importRootModel));
							}
						};
	            	}
	            }
	            
	            //获取需要导入的父节点路径
	            String rootPath = getTreeNodePath("",selectNode);
	            //获取当前导入节点的路径
	            String childPath = getTreeNodePath("",importRootNode);
	            //生成新的业务模型路径
	            String newObjPath = rootPath + childPath.substring(0,childPath.lastIndexOf("/"));
	            importRootModel.setObj_path(newObjPath);
	            importRootNode.setUserObject(importRootModel);
	            
	            importDataFile(bkfmImpEntity,importRootNode,selectNode,executeSqlList);
	            
	            //批量执行sql
	            localSqlHepler.getDBUtils().batch(executeSqlList);
	            for(BatchSqlEntity entity:executeSqlList) {
	            	System.out.println(entity.getSql());
	            	System.out.println(entity.getParams()[0]);
	            }
	            
	            //获取选中节点，并且将生成的新节点添加为选中节点的子节点
	            selectNode.add(importRootNode);
	            treePanel.refreshSelectNode(selectNode);
	        }
		}catch(Exception e) {
			logger.error("导入业务模型异常",e);
        	DesignUtils.showMessage(MainFrame.getMainFrame(), "导入业务模型异常",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
		}
	}
	
	private static String getTreeNodePath(String rootPath,DefaultMutableTreeNode node) {
		BlkTableMetaData model = (BlkTableMetaData)node.getUserObject();
		String treePath = "";
		treePath = model.getEn_us()+"/"+rootPath;
		DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode)node.getParent();
		if(parentNode !=null) {
			treePath = getTreeNodePath(treePath,parentNode);
		}
		return treePath;
		
	}
	
	/**
	 * 导入文件内容到业务模型节点
	 * @param parentBkfmImpEntity
	 * @param parentNode
	 * @throws Exception
	 */
	public static void importDataFile(BlkImportTableMetaData parentBkfmImpEntity,DefaultMutableTreeNode parentNode,DefaultMutableTreeNode selectNode,List<BatchSqlEntity> executeSqlList)throws Exception{
		for(BlkImportTableMetaData bkfmImpEntity : parentBkfmImpEntity.getChildArray()) {
			DefaultMutableTreeNode childNode = new DefaultMutableTreeNode();
			BlkTableMetaData childModel = new BlkTableMetaData();
            BeanUtils.copyProperties(bkfmImpEntity, childModel);
            //将新导入的节点置new
            childModel.setModel_states(ModelStates.NEW);
            childNode.setUserObject(childModel);
            parentNode.add(childNode);
            //需要将新生成的节点存放到数据库中
            //代码这里添加
            if(childModel.getModel_type() == ModelType.ATTRIBUTE) {
            	//插入字段
            	executeSqlList.add(localSqlHepler.getInsertFieldSql(childModel));
            }else if(childModel.getModel_type() == ModelType.TABLE || childModel.getModel_type() == ModelType.VIEW){
            	//插入表,要判断表名是否已经存在了，如果存在需要弹出提示让用户重新输入一个新的表名
            	if(localSqlHepler.queryTableOrViewExists(childModel)) {
    				new ProtyDialog("表或视图："+childModel.getEn_us()+",已经存在,请重新定义",ModelType.TABLE){
						@Override
						public boolean beforeCallBack(String zhText, String enText)throws Exception {
							BlkTableMetaData checkMetaData = new BlkTableMetaData();
							checkMetaData.setEn_us(enText);
							checkMetaData.setZh_cn(zhText);
							checkMetaData.setFather_tablemetadata_id(childModel.getFather_tablemetadata_id());
							if(localSqlHepler.queryTableOrViewExists(checkMetaData)) {
								DesignUtils.showMessage(MainFrame.getMainFrame(), "系统警告，节点："+checkMetaData.getEn_us()+",已经存在,请重新命名",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
								return false;
							}
							return true;
						}
						
						public void callBack(String zhText,String enText)throws Exception {
							childModel.setEn_us(enText);
							childModel.setZh_cn(zhText);
							executeSqlList.add(localSqlHepler.getInsertTableNodeSql(childModel));
						}
					};
            	}
            }else {
            	//插入节点
            	executeSqlList.add(localSqlHepler.getinsertNodeNoNewIdSql(childModel));
            }
			if(bkfmImpEntity.getChildArray().size()>0) {
				//递归
				importDataFile(bkfmImpEntity,childNode,selectNode,executeSqlList);
			}
			
			//获取需要导入的父节点路径
            String rootPath = getTreeNodePath("",selectNode);
            //获取当前导入节点的路径
            String childPath = getTreeNodePath("",childNode);
            //生成新的业务模型路径
            String newObjPath = rootPath + childPath.substring(0,childPath.lastIndexOf("/"));
            childModel.setObj_path(newObjPath);
			childNode.setUserObject(childModel);
            //将子节点添加到父节点中
            //parentNode.add(childNode);
		}
	}
	
	
	
	/**
	 * 节点导出
	 */
	public static void parseExpNode() {
		//定义json对象
		JSONObject bkfmTableMetaJson = new JSONObject();
		
		//当前节点
		TreeModelPanel treePanel = TreeModelPanel.newInstance();
		DefaultMutableTreeNode selectNode = treePanel.getSelectTreeNode();
		BlkTableMetaData selectModel = (BlkTableMetaData)selectNode.getUserObject();
		selectModel.setTablemetadata_id(DesignUtils.getRandom());
		bkfmTableMetaJson = JSONObject.fromObject(selectModel);
		bkfmTableMetaJson.put("childArray", new JSONArray());
		
		getExpNode(selectNode,selectModel,bkfmTableMetaJson);
		JFileChooser chooser = new JFileChooser();// 创建文件选择器
		FileNameExtensionFilter filter = new FileNameExtensionFilter(
		        ".bkfm", "bkfm");
		chooser.setFileFilter(filter);
        int option = chooser.showSaveDialog(MainFrame.getMainFrame());// 打开文件保存对话框
        if (option == JFileChooser.APPROVE_OPTION) {// 处理文件保存操作
            File file = chooser.getSelectedFile();// 获取用户选择的文件
            String fname = chooser.getName(file);
            if(fname.indexOf(".bkfm")==-1){
				file=new File(chooser.getCurrentDirectory(),fname+".bkfm");
			}
            try {
                FileOutputStream fout = new FileOutputStream(file);// 创建该文件的输出流
                //导出的文件结果des加密
                String des_entry_String = DESUtils.encryption(bkfmTableMetaJson.toString());
                fout.write(ApplicationUtils.str2HexadecimalStr(des_entry_String).getBytes());// 把文本保存到文件
                fout.flush();
                fout.close();
            } catch (Exception e) {
            	logger.error("导出业务模型异常",e);
            	DesignUtils.showMessage(MainFrame.getMainFrame(), "导出业务模型异常",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
            }
        }
	}
	
	/**
	 * 递归循环需要导出的子节点
	 * @param parentTreeNode
	 * @param parentModel
	 * @param bkfmTableMetaJson
	 */
	public static void getExpNode(DefaultMutableTreeNode parentTreeNode,BlkTableMetaData parentModel,JSONObject bkfmTableMetaJson) {
		JSONArray childArray = bkfmTableMetaJson.getJSONArray("childArray");
		for(int i=0;i<parentTreeNode.getChildCount();i++) {
			DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)parentTreeNode.getChildAt(i);
			BlkTableMetaData childModel = (BlkTableMetaData)childNode.getUserObject();
			//设置新的主键
			childModel.setTablemetadata_id(DesignUtils.getRandom());
			//设置节点所属父节点
			childModel.setFather_tablemetadata_id(parentModel.getTablemetadata_id());
			JSONObject childBkfmTableMetaJson = JSONObject.fromObject(childModel);
			childBkfmTableMetaJson.put("childArray", new JSONArray());
			childArray.add(childBkfmTableMetaJson);
			
			if(childNode.getChildCount()>0) {
				//递归循环
				getExpNode(childNode,childModel,childBkfmTableMetaJson);
			}
		}
	}

	/**
	 * 提交本地缓存到服务器数据库，同步建模结构
	 */
	public static void submitServerDB(){
		try {
			int result = DesignUtils.showSubmitConfirm(MainFrame.getMainFrame(), "是否确定需要提交本次业务模型？");
			if(result == JOptionPane.YES_OPTION){
				//全部提交，包括数据库结构
				new SubmitDialog(SubmitDialog.SUBMIT_TYPE_ALL);
			}else if(result == JOptionPane.NO_OPTION){
				//提交业务模型数据
				new SubmitDialog(SubmitDialog.SUBMIT_TYPE_BUSINESS_MODEL);
			}
		}catch(Exception e) {
			logger.error("提交业务建模异常",e);
			e.printStackTrace();
		}
	}
	
	/**
	 * 初始化服务器数据库
	 */
	public static void initServerDB(){
		if(DesignUtils.showConfirm(MainFrame.getMainFrame(), "请慎用改功能！是否确定初始化系统业务模型，确认后系统将恢复到默认阶段，现有的所有数据将被覆盖，并且数据不可恢复！") == JOptionPane.OK_OPTION){
				new Thread() {
					public void run(){
						try{
							//初始化本地缓存数据
							logger.info("初始化本地数据");
							DBSQLService.getLocalDBService().getDBUtils().batch(InitDesignConfig.getLocalDBDataSql());
							//将本地缓存数据库数据记录状态全部标记为new
							DBSQLService.getLocalDBService().getDBUtils().execute("UPDATE BLK_TABLE_METADATA SET MODEL_STATES='"+ModelStates.NEW.getIndex()+"'");
							//初始化数据库
							logger.info("初始化服务器数据");
							DBSQLService.getDBService().initServerDB();
							logger.info("初始化服务器数据库成功");
							//自动提交业务模型
							new SubmitDialog(true).run();
							logger.info("初始化服务器数据");
							DBSQLService.getDBService().getDBUtils().batch(InitDesignConfig.getServerDBDataSql());
							DesignUtils.showMessage(MainFrame.getMainFrame(), "初始化服务器数据库成功,请重启启动系统",DesignConstant.PROMIT_TITLE, JOptionPane.INFORMATION_MESSAGE);
							System.exit(0);
						}catch(Exception e){
							DesignUtils.showMessage(MainFrame.getMainFrame(), "初始化服务器数据库失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
							logger.error("初始化服务器数据库异常",e);
						}
					}
				}.start();
		}
	}
	
	/**
	 * 同步服务器模型数据到本地
	 */
	public static void sameServerDBToLocal() {
		if(DesignUtils.showConfirm(MainFrame.getMainFrame(), "是否确定需要同步服务器业务模型到本地？同步后将覆盖本地业务模型，系统建议请先备份！") == JOptionPane.OK_OPTION){
			new Thread() {
				public void run(){
					try{
						logger.info("开始备份本地业务模型");
						//备份本地数据库
						File local_db_file = new File(DBSQLService.LOCAL_DB_FILE);//127.0.0.1-bkfm-20180814145155
						SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
						String bak_version = "("+DBSQLService.getDBService().getDBServerIP()+"【"+DBSQLService.getDBService().getDBServerName()+"】"+df.format(new Date())+")";
						String new_local_db_file = local_db_file.getParentFile().getAbsolutePath()+"\\"+bak_version+local_db_file.getName();
						File bak_local_db_file = new File(new_local_db_file);
						FileUtils.copyFile(local_db_file, bak_local_db_file);
						logger.info("开始同步服务器数据模型到本地");
						//下载服务器数据库模型到本地
						DBSQLService.getLocalDBService().getDBUtils().execute("DELETE FROM BLK_TABLE_METADATA");
						DBSQLService.getLocalDBService().getDBUtils().execute("DELETE FROM BLK_TABLE_VERSION");
						List<BlkTableMetaData> serverDataList = DBSQLService.getDBService().getDBUtils().getBeanList("SELECT * FROM BLK_TABLE_METADATA ", BlkTableMetaData.class);
						for(BlkTableMetaData blkTableMetaData : serverDataList) {
							if(blkTableMetaData.getModel_type() == ModelType.TABLE || blkTableMetaData.getModel_type() == ModelType.VIEW) {
								DBSQLService.getLocalDBService().insertTableNodeNoNewId(blkTableMetaData);
							}else if(blkTableMetaData.getModel_type() == ModelType.ATTRIBUTE) {
								DBSQLService.getLocalDBService().insertField(blkTableMetaData);
							}else {
								DBSQLService.getLocalDBService().insertNodeNoNewId(blkTableMetaData);
							}
						}
						
						//版本信息
						Map<String,String> versionMap = DBSQLService.getDBService().getDBUtils().getItemMap("SELECT * FROM BLK_TABLE_VERSION");
						String db_version = versionMap.get("DB_VERSION");
						Object param [] = {db_version};
						DBSQLService.getLocalDBService().getDBUtils().execute("INSERT INTO BLK_TABLE_VERSION(DB_VERSION) VALUES(?)", param);
						logger.info("同步服务器模型数据到本地完成");
						DesignUtils.showMessage(MainFrame.getMainFrame(), "同步服务器模型数据到本地完成,请重启启动系统",DesignConstant.PROMIT_TITLE, JOptionPane.INFORMATION_MESSAGE);
						System.exit(0);
					}catch(Exception e){
						DesignUtils.showMessage(MainFrame.getMainFrame(), "初始化服务器数据库失败",DesignConstant.PROMIT_TITLE, JOptionPane.ERROR_MESSAGE);
						logger.error("同步服务器模型数据到本地异常",e);
					}
				}
			}.start();
		}
	}
}
